<?php
/*********************************************
 *  CPG Dragonfly™ CMS
 *********************************************
	Copyright © since 2010 by CPG-Nuke Dev Team
	http://dragonflycms.org

	Dragonfly is released under the terms and conditions
	of the GNU GPL version 2 or any later version
*/

namespace Poodle\Auth;

abstract class Provider extends \Poodle\Auth
{
	protected
		// from auth_providers table
		$id    = 0,
		$class = '',
		$mode  = 1,
		$name  = '',
		// from auth_identities table
		$password = null,
		// Generated with auth_providers_detect table
		$discover_uri = null,
		$identifier = null;

	function __construct(array $config=array())
	{
		foreach ($config as $k => $v) { $this->$k = $v; }
		if (!$this->id) {
			$this->id = self::getIdByClass(get_class($this));
		} else {
			$this->id   = (int)$this->id;
			$this->mode = (int)$this->mode;
		}
	}

	public function __get($key)
	{
		if (property_exists($this, $key)) return $this->$key;
		return null;
	}

	abstract public function getAction(array $credentials=array());

	abstract public function authenticate($credentials);

	public static function validClaimedId($id) { return false; }

	public static function getById($id)
	{
		$id = (int)$id;
		$SQL = \Poodle::getKernel()->SQL;
		$result = $SQL->uFetchAssoc("SELECT
			auth_provider_id id,
			auth_provider_class class,
			auth_provider_name name
		FROM {$SQL->TBL->auth_providers}
		WHERE auth_provider_id={$id} AND auth_provider_mode>0");
		return $result ? new $result['class']($result) : null;
	}

	public static function getIdByClass($class)
	{
		$SQL = \Poodle::getKernel()->SQL;
		$id = $SQL->uFetchRow("SELECT auth_provider_id FROM {$SQL->TBL->auth_providers} WHERE auth_provider_class=".$SQL->quote($class));
		return $id ? (int)$id[0] : false;
	}

	public static function getPublicProviders()
	{
		$SQL = \Poodle::getKernel()->SQL;
		return $SQL->uFetchAll("SELECT
			auth_provider_id id,
			auth_provider_class class,
			auth_provider_mode mode,
			auth_provider_name name
		FROM {$SQL->TBL->auth_providers}
		WHERE auth_provider_mode & 1");
	}

	public static function getAdminProviders()
	{
		$SQL = \Poodle::getKernel()->SQL;
		return $SQL->uFetchAll("SELECT
			auth_provider_id id,
			auth_provider_class class,
			auth_provider_mode mode,
			auth_provider_name name
		FROM {$SQL->TBL->auth_providers}
		WHERE auth_provider_mode & 2");
	}
}
